//
//  SeekoIntroViewController.m
//  Moko
//
//  Created by cj848 on 11. 7. 18..
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "SeekoIntroViewController.h"
#import "MokoAppDelegate.h"
#import "Reachability.h"
#import "HTMLParser.h"
#import "ParsingDirector.h"

@implementation SeekoIntroViewController

-(void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    GET_APPDELEGATE;
    if( alertView.tag == 300 ){
        // 재시도
        if( buttonIndex == 1 ) {
            [delegate.httpClient requestURL:delegate.configVO.siteHostAddress httpMethod:@"GET" bodyData:nil isMultiPart:NO boundary:nil target:self selector:@selector(finishLoading:)];
            alertView.tag = 200;
        }
    }
    else if( alertView.tag == 200 && buttonIndex == 0 ) {
        // 자동 로그인 체크 돼 있을 경우 로그인
        if( [delegate.configVO.autoLogin boolValue] == YES ) {
            NSString* action = [NSString stringWithFormat:@"%@/zboard4/login_check.php?user_id=%@&password=%@", delegate.configVO.siteHostAddress, delegate.configVO.username, delegate.configVO.password];
            [delegate.httpClient requestURL:action httpMethod:@"GET" bodyData:nil isMultiPart:NO boundary:nil target:self selector:@selector(autoLoginFinished:)];
        }
        else 
            [delegate.httpClient requestURL:delegate.configVO.siteHostAddress httpMethod:@"GET" bodyData:nil isMultiPart:NO boundary:nil target:self selector:@selector(finishLoading:)];

    }
}

// 기본적으로 오버라이드 돼야 할 메소드
- (void)finishLoading:(NSData*) data {
    // 기본적으로 커넥션과 데이터를 릴리즈 해야된다.
    ParsingDirector* director = [ParsingDirector sharedParsingDirector];
    director.responseData = data;
    NSArray* menus = [director getMenu];
    [data release];
    GET_APPDELEGATE;
    delegate.tabBarController = [[SeekoTabBarController alloc] initWithMenus:menus];
    [self.view removeFromSuperview];
    
    // 여기에 로그인 창으로 갈것인가 확인후에 가야되면 로그인을 모달로 띄울 예정
    [delegate.rootViewController.view addSubview:delegate.tabBarController.view];
}

- (void)dealloc
{
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle


// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView
{
    UIImage* img = [UIImage imageNamed:@"intro_seeko.png"];
    UIImageView* imageView = [[UIImageView alloc] initWithImage:img];
    self.view = imageView;
    self.view.frame = [[UIScreen mainScreen] bounds];
    [imageView release];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    int nResult = [[Reachability reachabilityForInternetConnection] currentReachabilityStatus];
    alert = [[UIAlertView alloc] initWithTitle:@"시코 모바일 어플 '모꼬'" message:@"환영합니다. 시코 모바일 어플 '모꼬'를 실행하셨습니다." delegate:self cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"OK", @"확인"), nil];
    alert.tag = 200;
    switch (nResult) {
        case NotReachable:
            [alert release];
            alert = [[UIAlertView alloc] initWithTitle:@"네트워크 상태 확인" message:@"네트워크 상태가 좋지 않습니다.\n연결을 확인하신 후 재시도 바랍니다." delegate:self cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"OK", @"확인"), @"재시도", nil];
            alert.tag = 300;
            
            break;
        case ReachableViaWWAN:
            [alert setMessage:[NSString stringWithFormat:@"%@\n와이파이 환경이 아닌 경우 가입된 요금제에 따라 과금이 될 수 있으니 유의하시기 바랍니다.", alert.message]];
            break;
    }
    
    [alert show];
    [alert release];
    alert = nil;
}
-(void)autoLoginFinished:(NSData*)data {
    GET_APPDELEGATE;
    NSArray* cookies = delegate.httpClient._cookies;
    for( NSHTTPCookie *cookie in cookies ) {
        if( [[cookie name] isEqualToString:@"user[id]"] ) {
            delegate.httpClient.isLogin = YES;
        }
        else if ([[cookie name] isEqualToString:@"user[name]"]) {
            delegate.httpClient.isLogin = YES;
        }
    }
    [delegate.httpClient requestURL:delegate.configVO.siteHostAddress httpMethod:@"GET" bodyData:nil isMultiPart:NO boundary:nil target:self selector:@selector(finishLoading:)];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    alert = nil;
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end